<?php
/**
 * 接口公共类
 */
namespace Api\Controller;
use Think\Controller;

class CommonController extends Controller{
	public $app_auth_id;//授权ID
	public $app_sign;//请求签名即公钥
	public $app_authtime;//认证时间戳 10位
	public $app_version;//APP版本号（内部版本号）
	public $app_type;//APP类型Android ios
	public $app_device;//APP设备信息
	public $app_token;//用户TOKEN
	public $app_os;//设备操作系统
	public $app_imei;//用户设备唯一标识
	public $app_city_id = 0;//用户城市ID
	public $current_get_score = 0;//当前获取得积分
	
	public function _initialize(){
		//获取接口参数配置信息
		$this->app_auth_id  = $_SERVER['HTTP_APP_AUTH_ID'] ? $_SERVER['HTTP_APP_AUTH_ID'] : '';
		$this->app_sign     = strtolower($_SERVER['HTTP_APP_SIGN']);
		$this->app_authtime = $_SERVER['HTTP_APP_AUTHTIME'] ? $_SERVER['HTTP_APP_AUTHTIME'] : '';
		$this->app_version  = $_SERVER['HTTP_APP_VERSION'] ? (int)$_SERVER['HTTP_APP_VERSION'] : '';
		$this->app_type     = $_SERVER['HTTP_APP_TYPE'] ? $_SERVER['HTTP_APP_TYPE'] : '';
		$this->app_imei     = $_SERVER['HTTP_APP_IMEI'] ? $_SERVER['HTTP_APP_IMEI'] : '';
		$this->app_device   = $_SERVER['HTTP_APP_DEVICE'] ? $_SERVER['HTTP_APP_DEVICE'] : '';
		$this->app_os       = $_SERVER['HTTP_APP_OS'] ? $_SERVER['HTTP_APP_OS'] : '';
		$this->app_token    = $_SERVER['HTTP_APP_TOKEN'] ? $_SERVER['HTTP_APP_TOKEN'] : '';
		$this->app_city_id  = $_SERVER['HTTP_APP_CITY_ID'] ? $_SERVER['HTTP_APP_CITY_ID'] : '';

		//去掉GET、POST里TP自觉参数
		unset($_GET['_URL_'],$_POST['_URL_']);

		//APP版本号，默认为1
		$this->app_version  = $this->app_version ? $this->app_version : 1;

		//APP类型，默认为Android
		$this->app_type    = $this->app_type ? strtolower($this->app_type) : 'android';
		//城市ID
		$this->app_city_id = $this->app_city_id ? $this->app_city_id : 0;

		//积分处理
		$this->current_get_score = D('UserScore')->role_update_score($this->user_id(false));

		//开启接口授权功能
		if(!Conf('api_auth_open', 'api')){
			return;
		}

		// $this->get_api_sign();
		// return;
		if($this->app_auth_id){
			if (!$this->app_sign) {
				$this->error('对不起，签名不能为空！', '', 501);
			}

			if (!is_numeric($this->app_authtime) || strlen($this->app_authtime) != 10) {
				$this->error('对不起，认证时间不能为空或有误！', '', 502);
			}

			if($this->is_api_sign_ok() == false){
				$this->error('对不起，您的签名有误！', '', 504);
			}
		}else{
			$this->error('授权ID不能为空', '', 500);
		}

	}
	/**
	 * 获取接口签名
	 */
	protected function get_api_sign(){
		//去掉GET、POST里TP自觉参数
		unset($_GET['_URL_'],$_POST['_URL_']);

		$appkey = $this->get_appkey();
		if(!$appkey){
			// return false;
		}
		// $appkey = 'ibuaiVcKdpRxkhJA';
		//获取GET参数
		// $params = $_GET;
		$params = '';
		foreach ($_GET as $key => $value) {
			$params[$key] = urldecode($value);
		}
		$debug['GET'] = $params;
		//获取签名参数
		$params['header_auth_id']      = $this->app_auth_id;
		$params['header_app_token']    = $this->app_token;
		$params['header_app_authtime'] = $this->app_authtime;
		$debug['params'] = $params;

		//将数组按abc顺序排序参数
		ksort($params);
		$debug['sort_params'] = $params;

		foreach ($params as $key => $value) {
			$url_arr[]= $key . '=' . $value;
		}
		$url_str = implode('&', $url_arr);
		
		//将数组转成URL参数字符串
		$url_params = $url_str . '&appkey=' . $appkey;
		$this->app_sign_url_str = $url_params;
		$debug['url_params'] = $url_params;
		//将URL参数字符串进行MD5密码
		$sign = md5($url_params);
		$debug['sign'] = $sign;

		$this->api_sign = $sign;
		// var_dump($debug);
		// var_dump($url_arr);
		// var_dump($url_str);
		// var_dump($sign);
		// exit;

		return $sign;
	}
	/**
	 * 判断接口签名是否正确
	 * @return boolean [description]
	 */
	protected function is_api_sign_ok(){
		$sign = $this->get_api_sign();
		if(!$sign){
			return false;
		}

		return $sign == $this->app_sign;
	}
	/**
	 * 获取APPKEY
	 * @param  string $auth_id 授权ID
	 */
	protected function get_appkey($auth_id = ''){
		$app_auth_id = $auth_id ? $auth_id : $this->app_auth_id;
		if(!$app_auth_id){
			return '';
		}

		$where['id']     = $app_auth_id;
		$where['status'] = 1;
		$appkey = D('ApiSet')->where($where)->getField('key');

		return $appkey;
	}
	//接口记录
	protected function logs($status,$info,$return_data){
		$data['source_id']   = $this->app_auth_id ? $this->app_auth_id : 0;
		$data['authkey']     = $this->app_sign ? $this->app_sign : '';
		$data['authtime']    = $this->app_authtime ? $this->app_authtime : '';
		$data['app_version'] = $this->app_version ? $this->app_version : '';
		$data['app_type']    = $this->app_type ? $this->app_type : '';
		$data['app_imei']    = $this->app_imei ? $this->app_imei : '';
		$data['app_device']  = $this->app_device ? $this->app_device : '';
		$data['app_os']      = $this->app_os ? $this->app_os : '';
		$data['app_token']   = $this->app_token ? $this->app_token : '';
		$data['module']      = strtolower(CONTROLLER_NAME);
		$data['action']      = strtolower(ACTION_NAME);
		$data['params']      = 'api_sign_url_str:' . $this->app_sign_url_str  . "\r\napi_sign:" . $this->api_sign  . "\r\nGET:" . print_r($_GET,true) . "\r\nPOST:" . print_r($_POST, true);
		//请求返回数据信息
		$data['return_status'] = $status;
		$data['return_info']   = $info;
		$data['return_data']   = '';//print_r($return_data,true);
		$data['create_time']   = time();
		if(Conf('api_logs_open', 'api')){
			D('ApiLogs')->add($data);
		}
	}
	protected function success($info='', $data='', $status=200){
		$this->logs($status, $info, $data);
		$json['data']   = $data ? $data : null;
		$json['status'] = $status;
		$json['info']   = $info;
		$json = $this->ajaxReturn($json, 'json', JSON_UNESCAPED_UNICODE);
	}
	protected function error($info='', $data='', $status=400){
		$this->logs($status, $info, $data);
		$json['data']   = $data ? $data : null;
		$json['status'] = $status;
		$json['info']   = $info;
		$json = $this->ajaxReturn($json, 'json', JSON_UNESCAPED_UNICODE);
	}
	protected function ReplaceUrl($data){
		$data = str_replace('/Public/Uploads/', Conf('UploadPath'), $data);
		return $data;
	}
	/**
	 * GET请求处理
	 * @param  string $field         get参数名
	 * @param  string $empty_msg     get值为空，提示信息
	 * @param  string $default_value get值为空，默认值
	 * @return [type]                返回参数值
	 */
	protected function _get($field,$empty_msg='', $default_value='', $eid=404){
		$value = trim(I('get.' . $field));
		if(!$value && $empty_msg){
			$this->error($empty_msg,'',$eid);
		}
		if(!$value){
			$value = $default_value;
		}
		return $value;
	}
	/**
	 * POST请求处理
	 * @param  string $field         post参数名
	 * @param  string $empty_msg     post值为空，提示信息
	 * @param  string $default_value post值为空，默认值
	 * @return [type]                返回参数值
	 */
	protected function _post($field,$empty_msg='', $default_value='', $eid=404){
		$value = trim(I('post.' . $field));
		if(!$value && $empty_msg){
			$this->error($empty_msg, '', $eid);
		}
		if(!$value){
			$value = $default_value;
		}
		return $value;
	}
	/**
	 * POST请求处理
	 * @param  string $field         post参数名
	 * @param  string $empty_msg     post值为空，提示信息
	 * @param  string $default_value post值为空，默认值
	 * @return [type]                返回参数值
	 */
	protected function _request($field,$empty_msg='',$default_value='',$eid=404){
		$value = trim(I('request.' . $field));
		if(!$value && $empty_msg){
			$this->error($empty_msg,'',$eid);
		}
		if(!$value){
			$value = $default_value;
		}
		return $value;
	}
	//获取当前用户城市ID
	protected function city_id(){
		$get_city_id  = $this->_get('city_id');
		$city_id      = $get_city_id ? $get_city_id : $this->app_city_id;
		$user_id      = $this->user_id(false);
		$user_city_id = D('User')->get_user_city_id($user_id);
		$city_id      = $city_id ? $city_id : $user_city_id;
		//默认为云南昭通
		return $city_id ? $city_id : 0;
	}
	//获取用户ID
	protected function user_id($is_login=true){
		$get_token  = $this->_get('token');
		$post_token = $this->_post('token');

		//从GET或POST获取token
		$token = $get_token ? $get_token : $post_token;
		//从header获取token
		$token = $this->app_token ? $this->app_token : $token;
		if(!$token && $is_login){
			$this->error('对不起，您尚未登录！', '', 202);
		}

		$where['token'] = $token;
		$info = D('UserToken')->where($where)->field('user_id,create_time')->find();
		if(!$info && $is_login){
			$this->error('登录超时，请重新登录[1]！', '', 202);
		}
		//判断是否超时（2小时）
		$conf_timeout = C('LOGIN_TIMEOUT');
		$conf_timeout = $conf_timeout ? $conf_timeout : 2 * 60 * 60;
		// var_dump($conf_timeout);exit;
		$is_timeout = (time() - $info['create_time']) > $conf_timeout;
		if($is_timeout && $is_login){
			$this->error('登录超时，请重新登录[2]！', '', 202);
		}
		if($is_login && $info){
			//刷新登录时间
			D('UserToken')->where($where)->save(array('create_time'=>time()));
		}
		
		return $info['user_id'] ? $info['user_id'] : 0;
	}
	/**
	 * 分页参数
	 * @param  [type] $count    记录总数
	 * @param  [type] $pagesize 每页数量
	 */
	protected function page_info($count, $pagesize){
		$data['page']       = $this->_get('page', '', 1);
		$data['pagesize']   = $pagesize;
		$data['total_page'] = ceil($count / $pagesize);
		$data['count']      = (int)$count;
		return $data;
	}
	/**
	 * 写入登录日志
	 * @param  [type] $user_id   用户ID
	 * @param  [type] $user_type 用户类型
	 * @param  [type] $token     Token
	 */
	protected function write_login_log($user_id,$user_type,$token,$login_type='mobile'){
		$app_type[1] = 'android';
		$app_type[2] = 'ios';
		$app_type[3] = 'web';
		
		$data['user_id']     = $user_id;
		$data['token']       = $token;
		$data['user_type']   = $user_type?$user_type:'';
		$data['app_type']    = $app_type[$this->app_type];
		$data['login_type']  = $login_type;
		$data['device']      = $this->app_device?$this->app_device:'';
		$data['os']          = $this->app_os?$this->app_os:'';
		$data['create_time'] = time();
		D('UserLoginLog')->add($data);
	}
	
}
?>